// pages/new/new.js
const app = getApp()
var util = require('../../utils/util.js');
import { HTTP } from '../../utils/https.js'
let http = new HTTP()

Page({
  data: {
    lineHeight: 24,
    functionShow: false,
    emojiShow: false,
    chatList:[],
    comment: '',
    keyboardHeight:'',
    keyboardHeightscroll:'70',
    focus: false,
    cursor: 0,
    _keyboardShow: false,
    emojiSource: 'https://huoxi.oss-cn-beijing.aliyuncs.com/cbb/159662117181730.jpg',
    parsedComment: [],
    height:'',
    id:'',
    user_id:'',
    page:1,
    total:1,
    toView:''
  },

  onLoad(options) {
    this.setData({
      id:options.id
    })
    const emojiInstance = this.selectComponent('.mp-emoji')
    this.emojiNames = emojiInstance.getEmojiNames()
    this.parseEmoji = emojiInstance.parseEmoji
    this.getChat(); 

    wx.setNavigationBarTitle({
      title: options.name//页面标题为路由参数
    });
  },
  onShow() {
    this.setData({
      user_id:wx.getStorageSync("user_id")
    })
  },
  getChat:function(){
    let that = this
    http.request({
      url: 'mini/v1/chat/chat',
      data:{user_id:that.data.id,page:that.data.page},
      success: function (res) {
        const data = res.data.data.reverse()
        that.setData({
          total:res.data.total
        })
        const datalist = that.data.chatList
        for (var i = 0; i < data.length; i++) {
          data[i].text = JSON.parse(data[i].text)
          data[i].created_at = util.timestampToTime(data[i].created_at)
          datalist.splice(0, 0, data[i]);
        } 
        
        that.setData({
          chatList:datalist,
          toView:that.data.page == 1 ? `chatlist${that.data.chatList.length-1}` : ''
        })
      }
    })
  },
  onkeyboardHeightChange(e) {
    const heights = e.detail.height
    this.setData({
      keyboardHeight: heights,
      height:heights,
      keyboardHeightscroll:this.data.chatList.length < 5 ? 70 : heights + 70
    })
  },
  hideAllPanel() {
    var that = this
    this.setData({
      functionShow: false,
      emojiShow: false,
      keyboardHeight:that.data.height,
      keyboardHeightscroll:this.data.chatList.length < 5 ? 70 : that.data.height + 70
    })
  },
  showEmoji() {
    this.setData({
      functionShow: false,
      keyboardHeight:0,
      keyboardHeightscroll:70,
      emojiShow: this.data._keyboardShow || !this.data.emojiShow
    })
  },
  showFunction() {
    this.setData({
      functionShow: this.data._keyboardShow || !this.data.functionShow,
      emojiShow: false
    })
  },
  chooseImage() {},
  onFocus() {
    this.data._keyboardShow = true
    this.hideAllPanel()
  },
  onBlur(e) {
    this.data._keyboardShow = false
    this.data.cursor = e.detail.cursor || 0
  },
  onInput(e) {
    const value = e.detail.value
    this.data.comment = value
  },
  onConfirm() {
    this.onsend()
  },
  insertEmoji(evt) {
    const emotionName = evt.detail.emotionName
    const { cursor, comment } = this.data
    const newComment =
      comment.slice(0, cursor) + emotionName + comment.slice(cursor)
    this.setData({
      comment: newComment,
      cursor: cursor + emotionName.length
    })
  },
  onsend() {
    const comment = this.data.comment
    const parsedComment = this.parseEmoji(this.data.comment)
    if(parsedComment.length == 0){
      return false
    }
    var that = this
    http.request({
      url: 'mini/v1/chat/send',
      data:{user_id:that.data.id,text:parsedComment},
      success: function (res) {
        const newData = {
          chat_id:that.data.chatList.length-1,
          created_at:util.formatTime(),
          friend_user_headimgurl:'',
          friend_user_id:'',
          my_user_headimgurl:wx.getStorageSync('headimgurl'),
          my_user_id:that.data.user_id,
          receive_user_id:'',
          send_user_id:that.data.user_id,
          text:parsedComment
        }
        
        that.setData({
          parsedComment,
          comment: '',
          chatList:that.data.chatList.concat(newData),
          toView:`chatlist${that.data.chatList.length}`
        })
      }
    })
  },
  deleteEmoji: function() {
    const pos = this.data.cursor
    const comment = this.data.comment
    let result = '',
      cursor = 0
    let emojiLen = 6
    let startPos = pos - emojiLen
    if (startPos < 0) {
      startPos = 0
      emojiLen = pos
    }
    const str = comment.slice(startPos, pos)
    const matchs = str.match(/\[([\u4e00-\u9fa5\w]+)\]$/g)
    // 删除表情
    if (matchs) {
      const rawName = matchs[0]
      const left = emojiLen - rawName.length
      if (this.emojiNames.indexOf(rawName) >= 0) {
        const replace = str.replace(rawName, '')
        result = comment.slice(0, startPos) + replace + comment.slice(pos)
        cursor = startPos + left
      }
      // 删除字符
    } else {
      let endPos = pos - 1
      if (endPos < 0) endPos = 0
      const prefix = comment.slice(0, endPos)
      const suffix = comment.slice(pos)
      result = prefix + suffix
      cursor = endPos
    }
    this.setData({
      comment: result,
      cursor: cursor
    })
  },
  scrolltolower:function(){
    this.setData({
      page: this.data.page + 1
    })

    if(this.data.total == this.data.chatList.length && this.data.total !== 0){
      return false
    }
    this.getChat()
  }
})
